<!-- 我的考试 -->
<template>
  <div class="exam-container">
    <div class="mg-b-8">
      <CustomTabs :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
    </div>
    <div class="flex-center">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item label="科室" prop="className">
          <px-select v-model="queryParams.className" style="width: 260px" placeholder="请选择科室" clearable>
            <px-option v-for="item in classNameList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="考试类别" prop="examType">
          <px-select v-model="queryParams.examType" style="width: 260px" placeholder="请选择考试类别" clearable>
            <px-option v-for="item in examTypeList" :key="item.value" :label="item.name" :value="item.name" />
          </px-select>
        </px-form-item>
        <px-form-item label="考试名称" prop="examName">
          <px-input v-model="queryParams.examName" style="width: 260px" placeholder="请输入考试名称" clearable />
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
    </div>
    <div v-loading="loading" class="table-content">
      <px-table height="calc(100vh - 360px)" :data="tableData" size="small" border class="common-table">
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="examName" label="考试名称" min-width="120" show-overflow-tooltip />
        <px-table-column prop="examCategoryId" label="考试类别" min-width="120" show-overflow-tooltip />

        <template v-if="activeName === 'F'">
          <px-table-column prop="departmentName" label="科室" min-width="120" show-overflow-tooltip />
          <px-table-column prop="duration" label="考试时长(分钟)" min-width="120" show-overflow-tooltip />
          <px-table-column prop="passScore" label="合格分数" min-width="120" show-overflow-tooltip />
          <px-table-column prop="leftTimes" label="剩余次数" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.defineTimes && scope.row.defineTimes === 0 ? "不限" : scope.row.leftTimes }}
            </template>
          </px-table-column>
          <px-table-column prop="overdueDaysText" label="距离考试结束剩余" min-width="120" show-overflow-tooltip>
            <template #default="scope"> {{ scope.row.overdueDaysText ?? "-" }}</template>
          </px-table-column>
        </template>

        <template v-if="activeName === 'P'">
          <px-table-column prop="score" label="考试成绩" min-width="120" show-overflow-tooltip />
          <px-table-column prop="endTime" label="完成时间" min-width="120" show-overflow-tooltip />
        </template>

        <px-table-column label="操作" width="80" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="开始考试" placement="top">
              <px-button v-if="activeName === 'F'" v-has="'ALL_EXAMMANAGE_MYEXAM_START_EXAM'" link type="primary" @click="handleToExam(scope.row)">
                <PublishIcon />
              </px-button>
            </px-tooltip>
            <!-- v-if="activeName === 'P'" -->
            <px-tooltip content="考试结果" placement="top">
              <px-button
                v-has="'ALL_EXAMMANAGE_MYEXAM_EXAM_RESULT'"
                :disabled="scope.row.state === 'N'"
                link
                type="primary"
                @click="handleViewResult(scope.row)"
              >
                <OffShelfIcon />
              </px-button>
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        class="table-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>

    <px-dialog v-model="examNoticeVisible" title="考试须知" width="800" @close="examNoticeVisible = false">
      <div>
        <div class="notice-line"><span class="notice-label">考试时间</span>{{ examData.duration }}分钟</div>
        <div class="notice-line"><span class="notice-label">合格分数</span>{{ examData.passScore }}</div>
        <div class="notice-line"><span class="notice-label">考试介绍</span>{{ examData.examIntro }}</div>
        <div class="notice-line"><span class="notice-label">注意事项</span>{{ examData.examNotice }}</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="examNoticeVisible = false">取消</px-button>
          <px-button type="primary" @click="toExam">开始</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup>
import { queryCurrentClassList, queryDictData } from "@/api/common";
import { getMyExamListAPI } from "@/api/knowledge/examManage";
import OffShelfIcon from "@/assets/svg/knowledge/offShelf.svg?component";
import PublishIcon from "@/assets/svg/knowledge/publish.svg?component";
import CustomTabs from "@/components/Tabs/index.vue";
import { PxMessage } from "px-ui";
import { onMounted, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();

defineOptions({
  name: "ALL_EXAMMANAGE_MYEXAM"
});

const formRef = ref(null);

const tabList = ref([
  { name: "F", label: "未通过" },
  { name: "P", label: "已通过" }
]);
const activeName = ref("F");

const state = reactive({
  loading: false,
  classNameList: [],
  examTypeList: [],
  queryParams: {
    className: "",
    examType: "",
    examName: ""
  },
  tableData: [],
  pageNum: 1,
  pageSize: 20,
  total: 10,
  examNoticeVisible: false,
  examData: {}
});
const { loading, classNameList, examTypeList, queryParams, tableData, pageNum, pageSize, total, examNoticeVisible, examData } = toRefs(state);

onMounted(() => {
  getClassNameSelect();
  getExamTypeList();
  handleQuery();
});

// 切换tab
const handelTabSelected = val => {
  activeName.value = val;
  handleQuery();
};

// 获取科室下拉框数据
const getClassNameSelect = async () => {
  const classNameData = await queryCurrentClassList();
  state.classNameList = [...classNameData];
};

// 获取考试类别下拉框数据
const getExamTypeList = async () => {
  const typeData = await queryDictData({ typeCode: "EXAM_TYPE" });
  state.examTypeList = [...typeData];
};

const userInfo = JSON.parse(localStorage.getItem("userInfo"));

// 查询
const handleQuery = async () => {
  try {
    state.loading = true;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      state: activeName.value,
      categoryId: state.queryParams.examType,
      department: state.queryParams.className,
      examName: state.queryParams.examName,
      examineeId: userInfo.userId
    };
    const res = await getMyExamListAPI(params);
    if (res?.data?.length) {
      let data = res?.data;
      data?.forEach(i => {
        if (i.overdueDays > 0) {
          i.overdueDaysText = i.overdueDays + "天";
        } else {
          i.overdueDaysText = "逾期" + Math.abs(i.overdueDays) + "天";
        }
      });
      state.tableData = data;
      state.total = res.total;
    } else {
      state.tableData = [];
      state.total = 0;
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 开始考试
const handleToExam = row => {
  if (row.leftTimes === 0 && row.defineTimes !== 0) {
    PxMessage.error("考试次数已耗尽，请联系管理员");
    return;
  }
  state.examData = row;
  state.examNoticeVisible = true;
};

const toExam = () => {
  router.push({
    path: "/all/knowledge/examManage/myExam/exam",
    query: {
      examId: state.examData.examId,
      examineeId: userInfo.userId
    }
  });
};

// 考试结果
const handleViewResult = row => {
  router.push({
    path: "/all/knowledge/examManage/myExam/examResult",
    query: {
      examId: row.examId,
      examineeId: userInfo.userId,
      clickSource: 1
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");

.notice-line {
  margin-bottom: 16px;
  color: rgb(0 0 0 / 80%);

  .notice-label {
    display: inline-block;
    width: 80px;
    margin-right: 10px;
    font-size: 14px;
    font-weight: 700;
    text-align: right;
  }
}
</style>

<style lang="scss">
.my-exam {
  .el-tabs__item.is-active {
    color: #409eff;
  }

  .el-tabs__item:hover {
    color: #409eff;
  }
}
</style>
